package com.thh.freemarker.controller;


import com.thh.freemarker.pojo.Student;
import com.thh.freemarker.service.PageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;


@Controller
@RequestMapping("freemarker")
public class FreemarkerController extends BaseController {

    @Autowired
    PageService pageService;


    //test1和preview方法效果是一样的 不一样的是 preview模板可能是存放在数据里的 而且数据对象是通过远程调用获取的

    //页面预览
    @RequestMapping(value="/preview/{pageId}",method = RequestMethod.GET)
    public void preview(@PathVariable("pageId") String pageId) throws IOException {
        //执行静态化
        String pageHtml = pageService.getPageHtml(pageId);
        //通过response对象将内容输出
        ServletOutputStream outputStream = response.getOutputStream();
        response.setHeader("Content-type","text/html;charset=utf-8");
        outputStream.write(pageHtml.getBytes("utf-8"));

    }


    //页面下载
    @RequestMapping(value="/download/{pageId}",method = RequestMethod.GET)
    public void download(@PathVariable("pageId") String pageId) throws IOException {
        //执行静态化
        String pageHtml = pageService.getPageHtml(pageId);
        //通过response对象将内容输出
        ServletOutputStream outputStream = response.getOutputStream();
        response.setHeader("Content-type","text/html;charset=utf-8");
        //控制下载文件的名字
        response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode("下载的名称.html", "UTF-8"));
        outputStream.write(pageHtml.getBytes("utf-8"));

    }








    @RequestMapping("/test1")
    public String freemarker(Map<String, Object> map){
        Map mapData = pageService.getModelByPageId("pageId");
        map.putAll(mapData);
        return "test1";
    }
}
